package cn.chenmanman.system.controller;

import cn.chenmanman.common.result.Result;
import cn.chenmanman.common.utils.JwtHelper;
import cn.chenmanman.common.utils.MD5;
import cn.chenmanman.model.system.SysUser;
import cn.chenmanman.model.vo.LoginVo;
import cn.chenmanman.system.exception.extend.BizException;
import cn.chenmanman.system.service.SysUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "登录相关接口")
@RestController
@RequestMapping("/admin/index")
public class IndexController {
    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){
        if (StringUtils.isEmpty(loginVo.getUsername()) || StringUtils.isEmpty(loginVo.getPassword())) {
            throw new BizException(20001, "用户名或密码未填写!");
        }
        SysUser user = sysUserService.getUserInfoByUserName(loginVo.getUsername());
        if (user == null) {
            throw new BizException(20001, "用户不存在!");
        }
        String md5Password = MD5.encrypt(loginVo.getPassword());
        if (!user.getPassword().equals(md5Password)){
            throw new BizException(20001, "密码不正确!");
        }
        if (user.getStatus().intValue() == 0) {
            throw new BizException(20001, "用户已禁用!");
        }
        String token = JwtHelper.createToken(user.getId(), user.getUsername());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("token", token);
        return Result.ok(map);
    }

    @GetMapping("/info")
    public Result info(HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        String username = JwtHelper.getUsername(token);
        Map<String, Object> map = sysUserService.getUserInfo(username);

        return Result.ok(map);
    }

    @PostMapping("/logout")
    public Result logout(){
        return Result.ok();
    }
}
